package pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes;

import org.unigrids.services.atomic.types.GridFileType;
import org.w3.x2005.x08.addressing.EndpointReferenceType;

import de.fzj.unicore.rcp.identity.IdentityActivator;
import de.fzj.unicore.uas.client.StorageClient;
import de.fzj.unicore.uas.util.AddressingUtil;
import de.fzj.unicore.wsrflite.xfire.ClientException;
import de.fzj.unicore.wsrflite.xmlbeans.BaseFault;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.utils.TreeUtils;
import pl.umk.mat.fred.unicore.urc.storagemanagement.unicore.Storage;

public class StorageNode extends Node {

	public static final String ICON_NAME = "icons/database.png";
	public static final String ICON_RED_NAME = "icons/database_red.png";
	public static final String ICON_GREEN_NAME = "icons/database_green.png";
	private Storage storage;
	private Long freeSpace;

	public StorageNode() {
		this.path = "";
	}
	
	public Storage getStorage() {
		return storage;
	}

	public void setStorage(Storage storage) {
		this.storage = storage;
	}
	
	public boolean listStorage() {
		StorageClient client = this.getStorage().getClient();
		try {
			if ((client == null) || !client.checkConnection()) {
				EndpointReferenceType epr = AddressingUtil.newEPR();
				epr.addNewAddress().setStringValue(this.getStorage().getUrl());
				client = new StorageClient(epr, IdentityActivator.getDefault().getUASSecProps(this.getStorage().getUrl()));
			}
			if ((client == null) || !client.checkConnection()) {
				// nie udalo sie stworzyc klienta
				return false;
			}
			
			this.setChildren(null);
			GridFileType[] files = client.listDirectory("");
			TreeUtils.addGridFileTypes(this, files);
			
			return this.getChildren().size() > 0;
		} catch (BaseFault e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public Long getFreeSpace() {
		return freeSpace;
	}

	public void setFreeSpace(Long freeSpace) {
		this.freeSpace = freeSpace;
	}
	
	@Override
	public StorageNode clone(Node nodeParent) {
		StorageNode storageNode = new StorageNode();
		storageNode.setParent(nodeParent);
		storageNode.setPath(this.getPath());
		storageNode.setFreeSpace(freeSpace);
		storageNode.setStorage(storage);
		for (Node n : this.getChildren()) {
			Node n2 = n.clone(storageNode);
			storageNode.add(n2);
		}
		return storageNode; 
	}
	
}
